<template>
  <view class="device-list-container">
    <view class="device-grid">
      <!-- Saved Devices -->
      <view
        v-for="device in savedDevices"
        :key="device.id"
        class="device-card"
        :class="{
          'is-connected': device.connected,
          'is-connecting': device.isConnecting
        }"
        @click="handleDeviceClick(device)">
        <view class="device-icon-wrapper">
          <image class="device-icon" src="/static/default.png" />
          <view
            v-if="device.connected || device.isConnecting"
            class="status-indicator"
            :class="{ connected: device.connected }"></view>
        </view>
        <text class="device-name">{{ device.name }}</text>
        <!-- <text class="device-id">{{ device.id }}</text> -->
        <text class="device-status">{{ getStatusText(device) }}</text>
        <button class="delete-btn" @click.stop="removeDevice(device.id)">{{ $t('blueDevice.delete') }}</button>
      </view>

      <!-- Add New Device Card -->
      <view class="device-card add-new" @click="addNewDevice">
        <div class="add-box">
          <view class="add-icon">+</view>
        </div>
        <text class="add-text">{{ $t('blueDevice.addNewDevice') }}</text>
      </view>
    </view>
  </view>
</template>

<!-- The <template> and <style> sections remain the same -->

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  // import VConsole from 'vconsole';
  import { useI18n } from 'vue-i18n'
  // 1. Import the new store
  import { bleStore } from '@/utils/ble-store' // Adjust the path if necessary
  const { t } = useI18n()
  // --- STATE MANAGEMENT, LIFECYCLE, UI HELPERS, LOCAL STORAGE (remain the same) ---
  const savedDevices = ref([])
  const STORAGE_KEY = 'nx_h5_bluetooth_devices'
  const SCAN_SERVICE_UUID = 0xfff0
  const COMM_SERVICE_UUID = '0000fff0-0000-1000-8000-00805f9b34fb'

  onMounted(() => {
    uni.setNavigationBarTitle({
      title: t('blueDevice.title')
    })
    if (typeof navigator.bluetooth === 'undefined') {
      uni.showToast({ title: t('blueDevice.webBluetoothNotSupported'), icon: 'none' })
      return
    }
    loadDevicesFromStorage()
    autoConnectToPermittedDevices()
    window.addEventListener('beforeunload', cleanupConnections)
    // new VConsole()
  })

  onUnmounted(() => {
    cleanupConnections()
    window.removeEventListener('beforeunload', cleanupConnections)
  })

  const getStatusText = device => {
    if (device.connected) return t('blueDevice.statusOnline')
    if (device.isConnecting) return t('blueDevice.statusConnecting')
    if (!device.device) return t('blueDevice.statusClickToAuth')
    return t('blueDevice.statusClickToConnect')
  }

  const loadDevicesFromStorage = () => {
    try {
      const devicesJson = localStorage.getItem(STORAGE_KEY)
      if (devicesJson) {
        const devices = JSON.parse(devicesJson)
        savedDevices.value = devices.map(d => ({
          ...d,
          device: null,
          connected: false,
          isConnecting: false
        }))
      }
    } catch (e) {
      console.error('Failed to load devices from storage:', e)
    }
  }

  const saveDevicesToStorage = () => {
    try {
      const devicesToStore = savedDevices.value.map(({ id, name }) => ({ id, name }))
      localStorage.setItem(STORAGE_KEY, JSON.stringify(devicesToStore))
    } catch (e) {
      console.error('Failed to save devices to storage:', e)
    }
  }

  // --- CORE BLUETOOTH FUNCTIONS (with navigation logic) ---

  const autoConnectToPermittedDevices = async () => {
    if (typeof navigator.bluetooth.getDevices !== 'function') {
      console.warn('navigator.bluetooth.getDevices() is not supported on this browser.')
      return
    }
    try {
      const permittedDevices = await navigator.bluetooth.getDevices()
      for (const permittedDevice of permittedDevices) {
        const savedDevice = savedDevices.value.find(d => d.id === permittedDevice.id)
        if (savedDevice) {
          savedDevice.device = permittedDevice
          // Don't navigate automatically, just establish the connection.
          // The user can then click to enter.
          await connectToDevice(savedDevice, false) // Pass false to prevent navigation
        }
      }
    } catch (error) {
      console.error(t('blueDevice.getPermittedFailed'), error)
    }
  }

  const handleDeviceClick = async device => {
    // 2. If already connected, set the device in the store and navigate
    if (device.connected) {
      console.log(t('blueDevice.deviceOnlineRedirecting'))
      bleStore.setActiveDevice(device.device)
      uni.navigateTo({
        url: '/pages/blue/index' // Make sure this path is correct
      })
      return
    }

    if (device.device) {
      await connectToDevice(device)
    } else {
      uni.showToast({ title: t('blueDevice.reAuthRequired', { deviceName: device.name }), icon: 'none' })
      await addNewDevice(true)
    }
  }

  const addNewDevice = async (isReAuth = false) => {
    try {
      const bluetoothDevice = await navigator.bluetooth.requestDevice({
        filters: [{ services: [SCAN_SERVICE_UUID] }],
        optionalServices: [COMM_SERVICE_UUID]
      })

      const existingDeviceIndex = savedDevices.value.findIndex(d => d.id === bluetoothDevice.id)
      if (existingDeviceIndex > -1) {
        const deviceToConnect = savedDevices.value[existingDeviceIndex]
        deviceToConnect.device = bluetoothDevice
        await connectToDevice(deviceToConnect)
      } else {
        const newDevice = {
          id: bluetoothDevice.id,
          name: bluetoothDevice.name || t('blueDevice.unknownDevice'),
          device: bluetoothDevice,
          connected: false,
          isConnecting: false
        }
        savedDevices.value.push(newDevice)
        saveDevicesToStorage()
        await connectToDevice(newDevice)
      }
    } catch (error) {
      if (error.name !== 'NotFoundError') console.error(t('blueDevice.addAuthFailed'), error)
    }
  }

  /**
   * Connects to a device and optionally navigates.
   * @param {object} device - The device to connect to.
   * @param {boolean} shouldNavigate - Whether to navigate after connecting. Defaults to true.
   */
  const connectToDevice = async (device, shouldNavigate = true) => {
    if (device.connected || device.isConnecting || !device.device) return
    const deviceIndex = savedDevices.value.findIndex(d => d.id === device.id)
    if (deviceIndex === -1) return

    try {
      savedDevices.value[deviceIndex].isConnecting = true
      device.device.addEventListener('gattserverdisconnected', () => onDisconnected(device.id))
      await device.device.gatt.connect()
      savedDevices.value[deviceIndex].connected = true

      // 3. After a successful connection, set device and navigate
      if (shouldNavigate) {
        bleStore.setActiveDevice(device.device)
        uni.navigateTo({
          url: '/pages/blue/index'
        })
      }
    } catch (error) {
      console.error(t('blueDevice.connectionFailed', { deviceName: device.name }), error)
    } finally {
      if (savedDevices.value[deviceIndex]) {
        savedDevices.value[deviceIndex].isConnecting = false
      }
    }
  }

  // --- Disconnect, Remove, and Cleanup functions remain the same ---
  const disconnectFromDevice = device => {
    if (device.device && device.device.gatt.connected) {
      device.device.gatt.disconnect()
    } else {
      onDisconnected(device.id)
    }
  }

  const removeDevice = deviceId => {
    const deviceIndex = savedDevices.value.findIndex(d => d.id === deviceId)
    if (deviceIndex > -1) {
      disconnectFromDevice(savedDevices.value[deviceIndex])
      savedDevices.value.splice(deviceIndex, 1)
      saveDevicesToStorage()

      uni.showToast({ title: t('blueDevice.deviceDeleted'), icon: 'success' })
    }
  }

  const onDisconnected = deviceId => {
    const deviceIndex = savedDevices.value.findIndex(d => d.id === deviceId)
    if (deviceIndex > -1) {
      savedDevices.value[deviceIndex].connected = false
      savedDevices.value[deviceIndex].isConnecting = false
    }
  }

  const cleanupConnections = () => {
    savedDevices.value.forEach(device => {
      if (device.connected) disconnectFromDevice(device)
    })
  }
</script>

<style scoped>
  /* Styles remain unchanged */
  .device-list-container {
    padding: 20rpx;
    background-color: #f7f7f7;
    min-height: 100vh;
    box-sizing: border-box;
  }

  .page-title {
    font-size: 40rpx;
    font-weight: bold;
    text-align: center;
    padding: 20rpx 0;
    margin-bottom: 20rpx;
  }

  .device-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }

  .device-card {
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.2s ease-in-out;
    border: 2rpx solid transparent;
    cursor: pointer;
  }
  .add-box {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .device-card.is-connected {
    border-color: #28a745;
    box-shadow: 0 4rpx 16rpx rgba(40, 167, 69, 0.2);
  }

  .device-card.is-connecting {
    border-color: #f39c12;
  }

  .device-icon-wrapper {
    position: relative;
    margin-bottom: 20rpx;
  }

  .device-icon {
    width: 100rpx;
    height: 100rpx;
  }

  .status-indicator {
    position: absolute;
    bottom: 5rpx;
    right: 5rpx;
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    border: 2rpx solid white;
    background-color: #f39c12; /* Connecting color */
  }

  .status-indicator.connected {
    background-color: #28a745;
  }

  .device-name {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }

  .device-id {
    font-size: 22rpx;
    color: #888;
    margin-top: 4rpx;
    word-break: break-all;
    text-align: center;
  }

  .device-status {
    font-size: 24rpx;
    margin-top: 10rpx;
    color: #555;
    font-weight: 500;
  }

  .delete-btn {
    margin-top: 20rpx;
    font-size: 24rpx;
    padding: 8rpx 30rpx;
    background-color: #ff4d4f;
    color: white;
    border-radius: 30rpx;
    border: none;
    cursor: pointer;
  }

  .device-card.add-new {
    border: 2rpx dashed #cccccc;
  }

  .add-icon {
    font-size: 80rpx;
    color: #cccccc;
    line-height: 1;
  }

  .add-text {
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #888;
  }
</style>
